import React, {
    Component,
} from 'react';

import {
    View,
    DeviceEventEmitter,
} from 'react-native';

import WebpImage from '../AnimalPlayer/WebpPlayer';
import { getFileExtension } from '../../actions/helpers';
import SvgaImage from '../AnimalPlayer/SvgaPlayer';
import {CustomCachedImage} from "react-native-img-cache";

import styles from './css/giftplayer';

export default class GiftPlayer extends Component {

    constructor(props){
        super(props);
        this.state = {
            url: "", //动画效果url
            animing_flg: false, //是否正在执行动画
            anim_list: [], //动画队列
        }
    }

    play(giftid){
        let url = "";
        if(typeof(this.props.giftAnim[giftid]) != "undefined"){
            url = this.props.giftAnim[giftid];
            if(!this.state.animing_flg){
                this.state.animing_flg = true;
                this.setState({url: url});
            }else{
                //加入动画队列
                this.state.anim_list.push(url);
            }
        }
    }

    componentWillMount(){
        //动画特效播放完毕
        DeviceEventEmitter.addListener('onAnimFinish', () => {
            let url = "";
            if(this.state.anim_list.length > 0){
                url = this.state.anim_list.pop();
            }
            //动画结束
            this.setState({url: url});
            if(url == ""){//结束动画队列
                this.state.animing_flg = false;
            }
        });
    }

    componentWillUnmount(){
        DeviceEventEmitter.removeListener('onAnimFinish', () => this.setState({url: ""}));
    }

    render(){
        return this.state.url ?
            <View style={styles.webpGift}>
            {getFileExtension(this.state.url)=="webp" ?
                <CustomCachedImage
                    component={WebpImage}
                    source={{uri: this.state.url}}
                    style={{width: "100%", height: "100%"}}
                ></CustomCachedImage>
            :
                <CustomCachedImage
                    component={SvgaImage}
                    source={{uri: this.state.url}}
                    style={{width: "100%", height: "100%"}}
                ></CustomCachedImage>
            }
            </View>
        : null
    }
}